package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author vvv
 * @date 2023-10-29 23 49
 * discription 第一个拦截器，拦截所以的请求，主要的作用是刷新用户状态
 */

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 拿到请求头里面的token
        String token = request.getHeader("authorization");
        // 2. 校验token
        if (StringUtils.isEmpty(token)) {
            return true;
        }
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        if (userMap.isEmpty()) {
            // 3.1 失败则放行让下一个拦截器去看是否要真正的拦截
            return true;
        }
        UserDTO userDTO = BeanUtil.toBean(userMap, UserDTO.class);
        // 3.2 成功则将用户数据保存到ThreadLocal中
        UserHolder.saveUser(userDTO);
        // 4. UV统计
        LocalDateTime now = LocalDateTime.now();
        String timeSuffix = now.format(DateTimeFormatter.ofPattern("yyyy:MM"));
        String key = RedisConstants.UV_STATISTICS + timeSuffix;
        stringRedisTemplate.opsForHyperLogLog().add(key, userDTO.getId().toString());
        // 5. 刷新redis中的用户凭证
        stringRedisTemplate.expire(tokenKey, 30, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
